/** 触底下拉 */
export interface ScrollHandlerInfo {
    // 指定监听的 dom 元素
    doc: HTMLElement | Element,
    // 触底时触发的 function 函数
    func?: () => void,
    // 允许的误差范围
    inaccuracy?: number,
    // 其他的判断条件
    otherJudgements?: {
        or?: boolean,
        and?: boolean,
        judgements: boolean
    },
    // 是否开启只触发向下滚动?
    onlyDown?: boolean
}

let oldScroll = 0, tempScroll = 0, isScrolledToBottom = false;

export function scrollHandler(scrollInfo: ScrollHandlerInfo) {
    const doc = scrollInfo.doc,
                scrollTop = doc.scrollTop,
                windowHeight = doc.clientHeight,
                scrollHeight = doc.scrollHeight,
                inaccuracy = scrollInfo.inaccuracy || 0;
  
  if (scrollTop + windowHeight >= scrollHeight - inaccuracy) {
      if ((scrollInfo.otherJudgements?.judgements && scrollInfo.otherJudgements?.and)) {
        // 或条件
        if (scrollInfo.func) {
            scrollInfo.func();
        }
      } else if ((scrollInfo.otherJudgements?.judgements && scrollInfo.otherJudgements?.or)) {
        // 且条件
        if (scrollInfo.func) {
            scrollInfo.func();
        }
      }
      if (!isScrolledToBottom && scrollInfo.func) {
        isScrolledToBottom = true;
        scrollInfo.func();
      }
    } else {
      isScrolledToBottom = false;
    }

    // let doc = scrollInfo.doc, otherJudgements = scrollInfo.otherJudgements, inaccuracy = scrollInfo.inaccuracy;
    // let scrollTop = doc.scrollTop, windowHeight = doc.clientHeight, scrollHeight = doc.scrollHeight;
    // // 相等说明不需要滚动条
    // if (scrollTop + windowHeight == scrollHeight) {
    //     return;
    // }
    // if (scrollInfo.onlyDown) {
    //     // 滚动条滚动的距离，如果当前滚动高度小于之前的滚动高度视为向上滚动
    //     let scrollStep = scrollTop - oldScroll;
    //     if (scrollStep <= 0) {
    //         oldScroll = 0;
    //         return;
    //     }
    //     // 更新 oldScroll
    //     oldScroll = scrollTop;
    // }
    // // 计算触底差值
    // let difference = inaccuracy ? Math.round(scrollTop + windowHeight) >= scrollHeight - inaccuracy : Math.round(scrollTop + windowHeight) >= scrollHeight;
    // if (tempScroll == Math.round(scrollTop + windowHeight)) { 
    //     return ;
    // };
    // if ((otherJudgements?.judgements && otherJudgements?.and) && difference) {
    //     // 或条件
    //     if (scrollInfo.func) {
    //         scrollInfo.func();
    //         tempScroll = Math.round(scrollTop + windowHeight)
    //     }
    // } else if ((otherJudgements?.judgements && otherJudgements?.or) || difference) {
    //     // 且条件
    //     if (scrollInfo.func) {
    //         scrollInfo.func();
    //     }
    // }
}